package controller

import (
	"cms/admin/request"
	"cms/admin/service"
	"cms/core/response"
	"cms/dao"
	"cms/store"
	"github.com/gin-gonic/gin"
	"strings"
)

func Check(ctx *gin.Context)  {
	tok := ctx.GetHeader("Authorization")
	if tok == "" {
		response.Success(ctx, gin.H{"ok": false})
		return
	}
	defer func() {
		if err := recover(); err != nil {
			response.Success(ctx, gin.H{"ok": false})
		}
	}()
	temps := strings.Split(tok, " ")
	user, err := store.GetAdminToken(temps[1])
	if err != nil {
		response.Success(ctx, gin.H{"ok": false})
		return
	}
	ctx.Set("admin_user", user)
	admin := service.GetCurrentAdmin(ctx)
	permissions := service.GetAdminPermissions(admin.Username)

	response.Success(ctx, gin.H{"ok": true, "user": admin, "permissions": permissions})
}

// Login 后台用户登陆
func Login(ctx *gin.Context)  {
	var r request.Login
	if err := ctx.ShouldBindJSON(&r); err != nil {
		response.Error(ctx, err.Error())
		return
	}
	tok, expire, err := dao.AdminLogin(r.Username, r.Password)
	if err != nil {
		response.Error(ctx, err.Error())
		return
	}

	response.Success(ctx, gin.H{
		"token": tok,
		"expire": expire,
	})
}

// EditPwd 修改密码
func EditPwd(ctx *gin.Context)  {
	service.GetCurrentAdmin(ctx)

	response.Success(ctx)
}

// Logout 注销登陆
func Logout(ctx *gin.Context)  {
	tok, ok := ctx.Get("admin_token")
	if !ok {
		response.Error(ctx, "未登陆")
		return
	}
	err := dao.AdminLogout(tok.(string))
	if err != nil {
		response.Error(ctx, err.Error())
		return
	}
	response.Success(ctx)
}
